package cc.rengu.igas.cops.core.service.trans.unionpay;

import cc.rengu.igas.cops.common.enums.RespCodeEnum;
import cc.rengu.igas.cops.facade.bean.OrderInfoBean;
import cc.rengu.igas.cops.facade.request.CheckUWQrCodeDataRequest;
import cc.rengu.igas.cops.facade.response.CheckUWQrCodeDataResponse;
import cc.rengu.igas.share.common.util.OpenEncyOrDecryptUtil;
import cc.rengu.igas.share.core.realize.impl.RiskMonitorServiceImpl;
import cc.rengu.oltp.service.base.BizBaseService;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.dao.UserOrderInfoMapper;
import cc.rengu.oltp.service.common.dao.impl.UserOrderInfoMapperImpl;
import cc.rengu.oltp.service.common.entity.UserOrderInfo;
import cc.rengu.oltp.service.common.enums.BizStatusEnum;
import cc.rengu.oltp.service.common.enums.OrderStatusEnum;
import cc.rengu.oltp.service.common.enums.TransStatusEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.service.model.RiskMonitorInfo;
import cc.rengu.oltp.service.realize.OrderService;
import cc.rengu.oltp.service.realize.RiskMonitorService;
import cc.rengu.oltp.service.realize.impl.OrderServiceImpl;
import cc.rengu.oltp.utility.util.*;
import com.alibaba.fastjson.JSON;

import java.util.HashMap;
import java.util.Map;

/**
 * 银联与微信条码互通功能
 * 支付页面解密手机银行的加密数据，并生成订单 *
 *
 * @author panky
 * @version 1.0.0 创建时间：2020/08/14
 */
public class CheckUWQrCodeDataService extends BizBaseService {

    @Override
    protected Object beforeBizProcess() throws Exception {
        CheckUWQrCodeDataRequest checkUWQrCodeDataRequest = new CheckUWQrCodeDataRequest();
        ConvertUtil.convertOutput(checkUWQrCodeDataRequest);
        return checkUWQrCodeDataRequest;
    }

    @Override
    protected BizResponse callBizService(Object request) throws Exception {
        CheckUWQrCodeDataRequest checkUWQrCodeDataRequest = (CheckUWQrCodeDataRequest) request;

        //参数jsonData为空
        if (StringUtil.isEmptyOrNull(checkUWQrCodeDataRequest.getJsonData())) {
            BizResponse response = new BizResponse();
            response.setRspSysId(AppParamConstant.IGAS);
            response.setRespDesc(RespCodeEnum.PARAM_ERROR.getRespCode());
            response.setRespDesc(RespCodeEnum.PARAM_ERROR.getRespDesc());
            return response;
        }

        //加密数据解密
        String jsonData = OpenEncyOrDecryptUtil.decryptByClusterKey(checkUWQrCodeDataRequest.getHeader().getInstId(),
                checkUWQrCodeDataRequest.getJsonData(),
                checkUWQrCodeDataRequest.getHeader().getSrcSysId(),
                checkUWQrCodeDataRequest.getHeader().getChanlId());
        Map<String, String> requestMap = JSON.parseObject(jsonData, Map.class);

        //银联交易流水号
        String txnNo = requestMap.get("txnNo");

        //交易流水号为空
        if (StringUtil.isEmptyOrNull(txnNo)) {
            BizResponse response = new BizResponse();
            response.setRspSysId(AppParamConstant.IGAS);
            response.setRespCode(RespCodeEnum.PARAM_ERROR.getRespCode());
            response.setRespDesc(RespCodeEnum.PARAM_ERROR.getRespDesc());
            return response;
        }

        //校验银联验签
        checkSign(requestMap);

        String instId = checkUWQrCodeDataRequest.getHeader().getInstId();
        UserOrderInfoMapper orderInfoMapper = new UserOrderInfoMapperImpl();
        UserOrderInfo opmsUserOrderInfo = orderInfoMapper.selectUserOrderInfoByPrimaryKey(instId, txnNo);

        CheckUWQrCodeDataResponse checkUWQrCodeDataResponse = null;
        if (opmsUserOrderInfo == null) {
            //新增订单
            UserOrderInfo userOrder = insertUserOrder(requestMap, checkUWQrCodeDataRequest);
            //订单格式转换
            checkUWQrCodeDataResponse = this.userOrderConvert(userOrder, requestMap);
        } else {
            //订单格式转换
            checkUWQrCodeDataResponse = this.opmsUserOrderConvert(opmsUserOrderInfo, requestMap);
        }
        BizResponse response = new BizResponse();
        response.setResult(checkUWQrCodeDataResponse);
        response.setRspSysId(AppParamConstant.IGAS);
        response.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        response.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        return response;
    }

    @Override
    protected void afterBizProcess(BizResponse response) throws Exception {
        CheckUWQrCodeDataResponse checkUWQrCodeDataResponse = new CheckUWQrCodeDataResponse();
        ConvertUtil.convertOutput(checkUWQrCodeDataResponse);
    }

    @Override
    protected RiskMonitorInfo getRiskMonitorInfo() {
        RiskMonitorInfo riskMonitorInfo = new RiskMonitorInfo();
        RiskMonitorService riskMonitorService = new RiskMonitorServiceImpl();
        riskMonitorInfo.setTransMonitor(riskMonitorService);
        return riskMonitorInfo;
    }

    //校验银联签名
    private void checkSign(Map<String, String> paramsMap) throws Exception {

    }

    /**
     * 生成或更新订单
     *
     * @param paramsMap
     * @return
     * @throws Exception
     */
    private UserOrderInfo insertUserOrder(Map<String, String> paramsMap, CheckUWQrCodeDataRequest checkUWQrCodeDataRequest) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        String instId = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.INST_ID);

        String orderType = paramsMap.get("orderType");//订单类型 支持 10、11、16
        String txnNo = paramsMap.get("txnNo");
        String paymentValidTime = paramsMap.get("paymentValidTime");//支付有效时间
        String payeeInfo = paramsMap.get("payeeInfo");//收款方信息
//        String acqCode = paramsMap.get("acqCode");//受理机构代码
        String txnAmt = paramsMap.get("txnAmt");//交易金额  单位为分
        String currencyCode = paramsMap.get("currencyCode");//交易币种
        String orderDesc = paramsMap.get("orderDesc");//订单描述
//        String customerIP = paramsMap.get("customerIP");//持卡人IP
        String userId = paramsMap.get("userId");//用户标识
//        String qrCodeType = paramsMap.get("qrCodeType");//二维码类型
        String orderNo = paramsMap.get("orderNo");//订单号 三方订单号
        String acqAddnData = paramsMap.get("acqAddnData");//收款方附加数据
        String frontUrl = paramsMap.get("frontUrl");//前台通知地址
        String merCatCode, id = null, name = null, nameEnd, termId, accNo, subId, subName, amount;

        //payeeInfo为base64加密，需解码
        //格式如下：{子域名1=值&子域名2=值&子域名3=值}
        Map<String, String> payeeInfoVo = new HashMap<String, String>();
        if (StringUtil.isEmptyOrNull(payeeInfo)) {
            payeeInfo = new String(StringUtil.base64StringToBinary(payeeInfo), "UTF-8");
            payeeInfo.replace("{", "").replace("}", "");
            String[] kvs = payeeInfo.split("\\&");
            for (String kv : kvs) {
                String[] kvAarry = kv.split("=");
                payeeInfoVo.put(kvAarry[0], kvAarry[1]);
            }
            id = payeeInfoVo.get("id");// 代码
            name = payeeInfoVo.get("name");//名称
            /*merCatCode = payeeInfoVo.get("merCatCode"); //类别
            nameEnd = payeeInfoVo.get("nameEnd");//英文名
            termId = payeeInfoVo.get("termId");//终端号
            accNo = payeeInfoVo.get("accNo");//卡号
            subId = payeeInfoVo.get("subId");//二级代码
            subName = payeeInfoVo.get("subName");//二级名称
            amount = payeeInfoVo.get("amount");//金额，只用于ATM取款场景*/
        }

        //保存订单
        UserOrderInfo userOrderInfo = new UserOrderInfo();
        userOrderInfo.setInstId(instId);// 机构标识
        userOrderInfo.setTxnDate(DateUtil.getCurrentDate());// 交易日期
        userOrderInfo.setTxnTime(DateUtil.getCurrentTime());// 交易时间
        userOrderInfo.setTxnNum(checkUWQrCodeDataRequest.getHeader().getTxnNum());// 内部交易码
        userOrderInfo.setBizType(checkUWQrCodeDataRequest.getHeader().getBizType());// 业务细分
        userOrderInfo.setMsgSrcId(checkUWQrCodeDataRequest.getHeader().getSrcSysId());// 源系统标识
        // 交易渠道标识(手机、直销等) ---行内的统一使用行号 没有渠道号
        userOrderInfo.setTransChannelId(checkUWQrCodeDataRequest.getHeader().getChanlId());
        userOrderInfo.setMchntOrderId(StringUtil.isEmptyOrNull(orderNo) ?
                checkUWQrCodeDataRequest.getHeader().getTraceNo() : orderNo); // 商户订单号不存子啊，使用系统流水号
        userOrderInfo.setOrderDesc(orderDesc);
        userOrderInfo.setUserId(userId);//用户编号
        // 平台商户/集团商户/代理商商户号
        userOrderInfo.setGroupMchntNo(id);
        // 平台商户/集团商户/代理商商户名称
        userOrderInfo.setGroupMchntName(name);
        // 订单币种
        userOrderInfo.setOrderCcy(currencyCode);
        // 订单金额
        userOrderInfo.setOrderAmt(AmountUtil.changeF2Y(txnAmt));
        // 待支付金额
        userOrderInfo.setNeedPayAmt(AmountUtil.changeF2Y(txnAmt));
        //系统流水号
        userOrderInfo.setSysSeqNum(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SYS_SEQ_NUM));
        //订单创建时间
        userOrderInfo.setOrderCreateTime(DateUtil.getCurrentDateTime("yyyyMMddHHmmss"));// 订单创建时间

        // 支付有效时间 单位秒
        if (cc.rengu.utility.base.StringUtil.isNullorEmpty(paymentValidTime)) {
            // 默认是3分钟
            paymentValidTime = "180";
        }
        int iQrValidTime = Integer.parseInt(paymentValidTime);
        // 交易序列号
        userOrderInfo.setOrderUrl(txnNo);
        // 订单有效时间
        userOrderInfo.setOrderExpiryTime(DateUtil.getDateByTimeStamp(System.currentTimeMillis() + iQrValidTime * 1000, "yyyyMMddHHmmss"));
        userOrderInfo.setOrderStatus(OrderStatusEnum.INIT.getStatus());
        userOrderInfo.setTransStatus(TransStatusEnum.TRANS_INIT.getStatus());
        // 01-业务处理中 40-授权未完成【待密码认证】
        userOrderInfo.setBizStatus(BizStatusEnum.PROCESSING.getStatus());
        // 订单类型
        // 10:一般消费 11:限定非贷记帐户支付的消费，例如购买理财产品 12:小微商户收款 20：ATM 31:人到人转账(不能使用贷记卡支付) 40：预授权交易
        userOrderInfo.setOrderType(orderType);
        // 创建时间
        userOrderInfo.setCreateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
        // 收款人信息JSON
        userOrderInfo.setRemark2(JSON.toJSON(payeeInfoVo).toString());

        userOrderInfo.setRemark2(acqAddnData);

        OrderService orderService = new OrderServiceImpl();
        /*注册登记订单*/
        if (!orderService.registerOrderInfo(userOrderInfo, null, null)) {
            rglog.error("订单创建失败");
            throw new BizException(RespCodeEnum.INSERT_PAY_ORDER_ERROR.getRespCode(), RespCodeEnum.INSERT_PAY_ORDER_ERROR.getRespDesc());
        }
        return userOrderInfo;
    }

    /**
     * @param userOrderInfo
     * @return
     * @throws Exception
     */
    private CheckUWQrCodeDataResponse userOrderConvert(UserOrderInfo userOrderInfo, Map<String, String> requestMap) throws Exception {
        CheckUWQrCodeDataResponse checkUWQrCodeDataResponse = new CheckUWQrCodeDataResponse();
        checkUWQrCodeDataResponse.setMchntNo(userOrderInfo.getGroupMchntNo());
        checkUWQrCodeDataResponse.setMchntName(userOrderInfo.getGroupMchntName());
        if (!StringUtil.isEmptyOrNull(requestMap.get("qrCodeType"))) {
            if (requestMap.get("qrCodeType").equals("0")) {
                checkUWQrCodeDataResponse.setQrType("1");
            } else {
                checkUWQrCodeDataResponse.setQrType("0");
            }
        }

        OrderInfoBean orderInfo = new OrderInfoBean();
        orderInfo.setTransDate(userOrderInfo.getTxnDate());
        orderInfo.setTransTime(userOrderInfo.getTxnTime());
        orderInfo.setTxnNum(userOrderInfo.getTxnNum());
        orderInfo.setMchntOrderId(userOrderInfo.getMchntOrderId());
        orderInfo.setOrderCcy(userOrderInfo.getOrderCcy());
        orderInfo.setOrderAmt(userOrderInfo.getOrderAmt());
        orderInfo.setOrderExpiryTime(userOrderInfo.getOrderExpiryTime());
        orderInfo.setOrderStatus(userOrderInfo.getOrderStatus());
        orderInfo.setBizStatus(userOrderInfo.getBizStatus());
        orderInfo.setOrderDesc(userOrderInfo.getOrderDesc());
        //设置前端通知地址
        //orderInfo.setFrontUrl( requestMap.get("fontUrl"));
        //orderInfo.setUserId( requestMap.get("userId") );
        checkUWQrCodeDataResponse.setOrderInfo(orderInfo);
        return checkUWQrCodeDataResponse;
    }


    /**
     * @param userOrderInfo
     * @return
     * @throws Exception
     */
    private CheckUWQrCodeDataResponse opmsUserOrderConvert(UserOrderInfo userOrderInfo, Map<String, String> requestMap) throws Exception {
        CheckUWQrCodeDataResponse checkUWQrCodeDataResponse = new CheckUWQrCodeDataResponse();
        checkUWQrCodeDataResponse.setMchntNo(userOrderInfo.getGroupMchntNo());
        checkUWQrCodeDataResponse.setMchntName(userOrderInfo.getGroupMchntName());
        if (!StringUtil.isEmptyOrNull(requestMap.get("qrCodeType"))) {
            if (requestMap.get("qrCodeType").equals("0")) {
                checkUWQrCodeDataResponse.setQrType("1");
            } else {
                checkUWQrCodeDataResponse.setQrType("0");
            }
        }

        OrderInfoBean orderInfo = new OrderInfoBean();
        orderInfo.setTransDate(userOrderInfo.getTxnDate());
        orderInfo.setTransTime(userOrderInfo.getTxnTime());
        orderInfo.setTxnNum(userOrderInfo.getTxnNum());
        orderInfo.setMchntNo(userOrderInfo.getGroupMchntNo());
        orderInfo.setMchntName(userOrderInfo.getGroupMchntName());
        orderInfo.setMchntOrderId(userOrderInfo.getMchntOrderId());
        orderInfo.setOrderCcy(userOrderInfo.getOrderCcy());
        orderInfo.setOrderAmt(userOrderInfo.getOrderAmt());
        orderInfo.setOrderExpiryTime(userOrderInfo.getOrderExpiryTime());
        orderInfo.setOrderStatus(userOrderInfo.getOrderStatus());
        orderInfo.setBizStatus(userOrderInfo.getBizStatus());
        orderInfo.setOrderDesc(userOrderInfo.getOrderDesc());
        //orderInfo.setUserId(userOrderInfo.getUserId());
        //设置前端通知地址
        //orderInfo.setFrontUrl( requestMap.get("fontUrl"));
        //orderInfo.setUserId( requestMap.get("userId") );
        checkUWQrCodeDataResponse.setOrderInfo(orderInfo);
        return checkUWQrCodeDataResponse;
    }
}
